<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-12-06 18:00:32
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Assets.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 单个牧场-打标资产
-->
<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { reactive, ref, PropType } from 'vue'
import { ElButton, ElTag } from 'element-plus'
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { zcAssetListApi } from '@/api/fa/earcon'
import { spEnclosureListApi } from '@/api/fa/enclosure'
import { required } from '@/utils/formRules'
import { useCache } from '@/hooks/web/useCache'
import { TableLxq } from '@/components/Lxq'
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
import { zcPastureListApi } from '@/api/fa/pasture'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const data = ref<any>({
  type: '1'
})
const rules = reactive({
  pasture_org_id: [required],
  admin_dept_id: [required],
  data: [required]
})
const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))
const newTreeData = ref<any[]>([])
const props = defineProps({
  data: {
    type: Array, // 栏位列表
    default: () => null
  },
  id: {
    type: Number,
    default: () => null
  },
  dataInfo: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})
const getListAsset = async (val) => {
  val.enclosure_id = '0'
  val.is_die = '0'
  val.pasture_org_id = data.value.pasture_org_id ? data.value.pasture_org_id : props.id
  return zcAssetListApi(val)
}
const {
  tableObject,
  methods,
  register: registerTable
} = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])

const onCustomer = async (value) => {
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    await DeptList(value)
    await getList()
    await getEnclosure(value)
    methodsForm.setValues(data.value)
  }
}
const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
}
// 管理员用户列表
const myUserListChange = async (value) => {
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const params = {
    org_id: wsCache.get('userInfo').default_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
  methodsForm.setValues(data.value)
}
const UserList = async (value) => {
  data.value.pasture_dept_id = value
  newUserData.value = []
  const params = {
    org_id: data.value.pasture_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}
const stateChangeAdminUser = async (value) => {
  data.value.admin_user_id = value
}
const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}

// const myDeptChange = async (value) => {
//   data.value.pasture_dept_id = value
//   methodsForm.setValues(data.value)
// }

const typeChange = async (value) => {
  data.value.type = value
  if (value == 1) {
    schema[2].hidden = true
  } else {
    schema[2].hidden = false
  }
}

const outEnclosure = async (value) => {
  data.value.in_enclosure_id = value
}
const time = async (value) => {
  data.value.date = value
  // if (data.value.type == 1) {
  //   schema[2].hidden = true
  // } else {
  //   schema[2].hidden = false
  // }
}
// const defaultProps = {
//   children: 'children',
//   label: 'class_name'
// }
const schema = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    },
    formItemProps: {
      rules: [required]
    }
  },
  {
    field: 'admin_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeAdminUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    },
    formItemProps: {
      rules: [required]
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    },
    formItemProps: {
      rules: [required]
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  // {
  //   field: 'pasture_dept_id',
  //   label: '我的部门',
  //   component: 'TreeSelect',
  //   componentProps: {
  //     data: myDeptList,
  //     'check-strictly': true,
  //     'default-expand-all': true,
  //     'node-key': 'dept_id',
  //     props: {
  //       children: 'children',
  //       label: 'dept_name'
  //     },
  //     onChange: myDeptChange
  //   },
  //   formItemProps: {
  //     rules: [required]
  //   }
  // },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    componentProps: {
      options: dict.enclosure_type,
      onChange: typeChange,
      disabled: true
    }
  },
  {
    field: 'in_enclosure_id',
    label: '栏位',
    component: 'TreeSelect'
    // hidden: false,
    // componentProps: {
    //   data: newTreeData,
    //   'check-strictly': true,
    //   'default-expand-all': true,
    //   'node-key': 'id',
    //   props: {
    //     children: 'children',
    //     label: 'name'
    //   },
    //   onChange: outEnclosure
    // },
    // formItemProps: {
    //   rules: [required]
    // }
  },
  {
    field: 'date',
    label: '时间',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYY-MM-DD',
      onChange: time
    },
    formItemProps: {
      rules: [required]
    }
  }
  // {
  //   field: 'number',
  //   label: '数量',
  //   component: 'Input',
  //   componentProps: {
  //     disabled: true
  //   }
  // }
])

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'pasture_org_name',
    label: '牧场名称',
    width: 220,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标编号',
    width: 200,
    search: {
      show: true
    }
  }
])
defineExpose({
  methods: methods,
  data
})

const { allSchemas } = useCrudSchemas(crudSchemas)
const { register, methods: methodsForm } = useForm({
  schema
})

const getRowKey = (row) => {
  return row.id
}

// watch(
//   () => props.data,
//   (value) => {
//     if (!value) return
//     newTreeData.value = [{ id: '0', name: '=== 顶级 ===' }, ...value]
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

// const newTreeData = ref<any[]>([])

const getEnclosure = async (val) => {
  const res = await spEnclosureListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log(res.data, 'res.data')
    newTreeData.value = [{ id: '0', name: '=== 顶级 ===' }, ...res.data]
  }
}

const init = async () => {
  data.value.type = '1'
  data.value.admin_dept_id = wsCache.get('userInfo').default_dept_id
  data.value.pasture_org_id = props.dataInfo.org_id
  data.value.pasture_org_name = props.dataInfo.org_name
  methodsForm.setValues(data.value)
  await getList()
  await getEnclosure(data.value.pasture_org_id)
}
init()

const getListAssetSelect = async () => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  await getList()
}
const getListAssetReste = async () => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  await getList()
}
</script>

<template>
  <ContentWrap title="主数据">
    <Form :rules="rules" @register="register" :data="data">
      <template #in_enclosure_id>
        <ElSelect v-model="data.in_enclosure_id" @change="outEnclosure">
          <ElOption v-for="item in newTreeData" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
              <ElTag :type="item.type == '1' ? 'success' : item.type == '2' ? 'warning' : 'danger'">
                {{ item.type == '1' ? '育肥' : item.type == '2' ? '低效' : '' }}
              </ElTag>
            </span>
          </ElOption>
        </ElSelect>
      </template>
    </Form>
  </ContentWrap>
  <ContentWrap title="选择资产">
    <div>
      <el-form :inline="true" :model="data" class="demo-form-inline">
        <el-form-item label="注射编号">
          <el-input v-model="data.asset_code" />
        </el-form-item>
        <el-form-item label="项圈编号">
          <el-input v-model="data.asset_code_2" />
        </el-form-item>
        <el-form-item label="耳标编号">
          <el-input v-model="data.earcon_code" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getListAssetSelect">查询</el-button>
          <el-button type="" @click="getListAssetReste">重置</el-button>
        </el-form-item>
      </el-form>
      <TableLxq
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        v-model:checkedAll="data.checkedAll"
        v-model:noSelectData="data.noSelectData"
        v-model:selectData="data.selectData"
        v-model:total="tableObject.count"
        v-model:tableLen="data.number"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
        @register="registerTable"
      />
    </div>
  </ContentWrap>
</template>
<style lang="less" scoped></style>
